package com.app.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import com.app.model.RoleUser;
import com.app.model.User;

@Repository
public class UserDao {
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	private class UserRowMapper implements RowMapper<User>{
		@Override
		public User mapRow(ResultSet rs, int rowNum) throws SQLException {
			User user = new User();
			user.setId(rs.getLong("id"));
			user.setName(rs.getString("name"));
			return user;
		}   
}

	public List<User> findAllByPage(String sql){
		//String final_sql = sql + String.format(" limit %d, %d ", start, pageSize);
		return jdbcTemplate.query(sql, new BeanPropertyRowMapper(User.class));
	}

	public Integer getCount(String sql) {
		return jdbcTemplate.queryForObject(sql, Integer.class);
	}

	public void save(User user) {
		String sql = "insert into auth_user(name,pwd) values(?,?)";  
        Object args[] = {user.getName(),user.getPwd()};  
        jdbcTemplate.update(sql, args);  
	}
	
	public void update(User user) {
		String sql = "update auth_user set name = ?,pwd = ? where id = ?";  
        Object args[] = {user.getName(),user.getPwd(),user.getId()};  
        jdbcTemplate.update(sql, args);  
	}
	
	//删除  
    public void delete(Long id) {  
        String sql = "delete from auth_user where id = ?";  
        Object args[] = new Object[]{id};  
        jdbcTemplate.update(sql,args);  
    }

	public User getById(Long id) {
		String sql = "select * from auth_user where id = ?";  
        Object args[] = new Object[]{id};  
        User  user = jdbcTemplate.queryForObject(sql,args,new BeanPropertyRowMapper(User.class));  
        return user;  
	}

	public RoleUser getRole(Long id) {
		String sql = "select * from auth_role_user where userId = ?";  
		Object args[] = new Object[]{id};  
		return jdbcTemplate.queryForObject(sql,args,new BeanPropertyRowMapper(RoleUser.class)); 
	}

	public Object getRoleList() {
		String sql = "select * from auth_role ";    
		return jdbcTemplate.query(sql,new BeanPropertyRowMapper(User.class));
	}

	public User getByName(String name) {
		String sql = "select * from auth_user where name = ?";  
        Object args[] = new Object[]{name};  
        /*List<User>  list = jdbcTemplate.query(sql,args,new BeanPropertyRowMapper(User.class));  
        if(CollectionUtils.isEmpty(list)){
        	return null;
        }*/
        return jdbcTemplate.queryForObject(sql,args,new BeanPropertyRowMapper(User.class)); 
	}  
}
